package com.microblogforsim.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.microblogforsim.R;
import com.microblogforsim.adapter.ImagePickerAdapter;
import com.microblogforsim.callback.JsonCallback;
import com.microblogforsim.imageloader.GlideImageLoader;
import com.microblogforsim.model.LzyResponse;
import com.microblogforsim.model.MyResponse;
import com.microblogforsim.model.User;
import com.microblogforsim.utils.ACache;
import com.microblogforsim.utils.FileType;
import com.microblogforsim.utils.QnUploadHelper;
import com.microblogforsim.utils.SelectDialog;
import com.microblogforsim.utils.Urls;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class PublishActivity extends AppCompatActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener,
        View.OnClickListener {
//    取消按钮
    private TextView btn_cancle;
//    发布用户
    private TextView tv_name;
//    发送按钮
    private TextView btn_send;
//    内容编辑框
    private EditText et_content;
//    获取定位按钮
    private TextView btn_where;
//    公开按钮
    private TextView btn_public;
//    底部菜单按钮组
    private ImageView btn_tupian,btn_aite,btn_huati,btn_biaoqing,btn_tianjia;
   private RecyclerView recyclerView;
    //图片选择
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 8;               //允许选择图片最大数
    //缓存
    private ACache aCache ;
    //七牛云
    final private String 	AccessKey = "rvIZAtJwNegAtaTGP3ndagqi30CFIH53n9wLDna0";
    final private String 	SecretKey = "87N6MEi_1Okkm7sarx6oh6L-Dg4jKgNymPvpU-ld";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_publish);
        init();
        initImagePicker();
        initWidget();

    }

    private void init() {
          aCache = ACache.get(PublishActivity.this);
        btn_cancle = findViewById(R.id.activity_publish_cancle);
        tv_name = findViewById(R.id.activity_publish_name);
        btn_send = findViewById(R.id.activity_publish_send);
        et_content = findViewById(R.id.activity_publish_content);
        btn_where = findViewById(R.id.activity_publish_where);
        btn_public = findViewById(R.id.activity_publish_public);
        btn_tupian = findViewById(R.id.activity_publish_img);
        btn_aite = findViewById(R.id.activity_publish_aite);
        btn_huati = findViewById(R.id.activity_publish_huati);
        btn_biaoqing = findViewById(R.id.activity_publish_biaoqing);
        btn_tianjia = findViewById(R.id.activity_publish_tianjia);

        btn_cancle.setOnClickListener(this);
        btn_send.setOnClickListener(this);
        btn_where.setOnClickListener(this);
        btn_public.setOnClickListener(this);
        btn_tupian.setOnClickListener(this);
        btn_aite.setOnClickListener(this);
        btn_huati.setOnClickListener(this);
        btn_biaoqing.setOnClickListener(this);
        btn_tianjia.setOnClickListener(this);
        //初始化七牛云
        QnUploadHelper.init(AccessKey,SecretKey);
        User user =(User ) aCache.getAsObject("UserInfo");
        if(user!=null){
            tv_name.setText(user.getUserName());
        }
    }
   private void UpQn(String url,String photoName){
       QnUploadHelper.uploadPic(url, photoName, new QnUploadHelper.UploadCallBack() {
           @Override
           public void success(String url) {

               Log.i("image_uri",url);
               Toast.makeText(PublishActivity.this, ""+url, Toast.LENGTH_SHORT).show();
           }

           @Override
           public void fail(String key, ResponseInfo info) {
               Log.i("key",key+info.error);
           }
       });

   }

   private  String qiniu(String path,String name){
      File   data = new File(path);
       String key = name;
       final String[] re_key = {""};
       QnUploadHelper qnUploadHelper= new QnUploadHelper();
       String token =qnUploadHelper.getUpToken();
       Configuration config = new Configuration.Builder()
               .connectTimeout(90)              // 链接超时。默认90秒
               .useHttps(true)                  // 是否使用https上传域名
               .useConcurrentResumeUpload(true) // 使用并发上传，使用并发上传时，除最后一块大小不定外，其余每个块大小固定为4M，
               .concurrentTaskCount(3)          // 并发上传线程数量为3
               .responseTimeout(90)             // 服务器响应超时。默认90秒
               .zone(FixedZone.zone2)           // 设置区域，不指定会自动选择。指定不同区域的上传域名、备用域名、备用IP。
               .build();
// 重用uploadManager。一般地，只需要创建一个uploadManager对象
       UploadManager uploadManager = new UploadManager(config);
       uploadManager.put(data, key, token,
               new UpCompletionHandler() {

                   @Override
                   public void complete(String key, ResponseInfo info, JSONObject res) {
                       //res包含hash、key等信息，具体字段取决于上传策略的设置
                       if(info.isOK()) {
                           Log.i("qiniu", "Upload Success");
                           re_key[0] = key;
                       } else {
                           Log.i("qiniu", "Upload Fail");
                           re_key[0] = "fail";
                           //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                       }
                       Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                   }
               }, null);
       return re_key[0];
   }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.activity_publish_cancle:
                finish();
                break;
            case R.id.activity_publish_send:
                Toast.makeText(this, "发送按钮", Toast.LENGTH_SHORT).show();
               if(images.size()>0){
                   Date date =  new Date();

                String result=  qiniu(images.get(0).path,date.getTime()+""+images.get(0).mimeType.replace("iamge/","."));
                   Toast.makeText(this, "result:"+result, Toast.LENGTH_SHORT).show();
               }
                break;
            case R.id.activity_publish_where:
                Toast.makeText(this, "定位按钮", Toast.LENGTH_SHORT).show();
                break;
            case R.id.activity_publish_public:
                Toast.makeText(this, "公开按钮", Toast.LENGTH_SHORT).show();
                break;
            case R.id.activity_publish_img:
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent1 = new Intent(PublishActivity.this, ImageGridActivity.class);
                /* 如果需要进入选择的时候显示已经选中的图片，
                 * 详情请查看ImagePickerActivity
                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                break;
            case R.id.activity_publish_aite:
                Toast.makeText(this, "@按钮", Toast.LENGTH_SHORT).show();
                break;
            case R.id.activity_publish_huati:
                Toast.makeText(this, "话题按钮", Toast.LENGTH_SHORT).show();
                break;
            case R.id.activity_publish_biaoqing:
                Toast.makeText(this, "表情按钮", Toast.LENGTH_SHORT).show();
                break;
            case R.id.activity_publish_tianjia:
                Toast.makeText(this, "添加按钮", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    /**
     * 初始化图片选择器
     */
    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    /**
     * 初始图片显示化适配器
     */
    private void initWidget() {
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        recyclerView.setVisibility(View.INVISIBLE);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    /**
     * 消息提示框
     * @param listener
     * @param names
     * @return
     */
    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent1 = new Intent(PublishActivity.this, ImageGridActivity.class);
                /* 如果需要进入选择的时候显示已经选中的图片，
                 * 详情请查看ImagePickerActivity
                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                //showDialog ,唤起提示框
//               showDialog(new SelectDialog.SelectDialogListener() {
//                    @Override
//                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                        switch (position) {
//                            case 0: // 直接调起相机
//                                /**
//                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
//                                 *
//                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
//                                 *
//                                 * 如果实在有所需要，请直接下载源码引用。
//                                 */
//                                //打开选择,本次允许选择的数量
//                                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
//                                Intent intent = new Intent(PublishActivity.this, ImageGridActivity.class);
//                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
//                                startActivityForResult(intent, REQUEST_CODE_SELECT);
//                                break;
//                            case 1:
//                                //打开选择,本次允许选择的数量
//                                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
//                                Intent intent1 = new Intent(PublishActivity.this, ImageGridActivity.class);
//                                /* 如果需要进入选择的时候显示已经选中的图片，
//                                 * 详情请查看ImagePickerActivity
//                                 * */
////                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
//                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
//                                break;
//                            default:
//                                break;
//                        }
//
//                    }
//                }, names);


                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    ArrayList<ImageItem> images = null;
    //在选择图片后返回本界面调用此方法
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                recyclerView.setVisibility(View.VISIBLE);
                if (images != null) {
                    selImageList.addAll(images);
                    Log.d("TAG", "onActivityResult: "+images.get(0).path);

                    Toast.makeText(this, ""+images.get(0).mimeType.replace("image/","."), Toast.LENGTH_SHORT).show();
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }
    }

}